#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include<unistd.h>
#include<fcntl.h>

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

#define PATH "."
#define FILENAME "filo"

#define CREATOR "creator"
#define USER "user"

class Fifo
{
public:
    Fifo(const std::string &path, const std::string &name, const std::string usetype)
        : _path(path), _name(name), _usetype(usetype)
    {
        _fifoname = _path + "/" + _name;
        if (_usetype == "creator")
        {
            umask(0);
            int n = mkfifo(_fifoname.c_str(), 0666);
            if (n < 0)
            {
                ERR_EXIT("mkfifo");
            }
            std::cout<<"mkfifo success!"<<std::endl;
        }
    }

    void OpenForRead()
    {
        _fd = open(_fifoname.c_str(),O_RDONLY);
        if(_fd < 0)
        {
            ERR_EXIT("open");
        }
        std::cout<<"open fifo success!"<<std::endl;
    }

    void OpenForWrite()
    {
        _fd = open(_fifoname.c_str(),O_WRONLY);
        if(_fd < 0)
        {
            ERR_EXIT("open");
        }
        std::cout<<"open fifo success!"<<std::endl;
    }

    void Write()
    {
        std::string message;
        while(true)
        {
            std::cout<<"Please enter the message:";
            std::getline(std::cin,message);
            write(_fd,message.c_str(),message.size());
        }
    }

    void Read()
    {
        while(true)
        {
            char buffer[1024];
            int n = read(_fd,buffer,sizeof(buffer)-1);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout<<"Client say:"<<buffer<<std::endl;
            }
            else if(n == 0)
            {
                std::cout<<"Client quit,me too!"<<std::endl;
                break;
            }
            else
            {
                std::cout<<"read error"<<std::endl;
                break;
            }
        }
    }

    void Close()
    {
        close(_fd);
    }

    ~Fifo() 
    {
        //std::cout<<"~Fifo"<<std::endl;
        if(_usetype == "user")
        {
            int n = unlink(_fifoname.c_str());
            if(n == -1)
            {
                ERR_EXIT("unlink");
            }
            std::cout<<"unlink success!"<<std::endl;
        }
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
    std::string _usetype;
};